/**
 * @(#) HomeMediator.as
 *
 * @date		2009. 02. 05
 * @version		1.0
 * @author		Shin, Yunwoo
 * @description	Home.mxml의 interface를 담당하는 Mediator
 * 				주로 메뉴를 처리한다. 
 */
package com.skt.common_hr.main.view
{
	import com.skt.common_hr.common.*;
	import com.skt.common_hr.common.events.AppMenuEvent;
	import com.skt.common_hr.common.puremvc.CommonMediator;
	import com.skt.common_hr.main.ApplicationFacade;
	import com.skt.common_hr.main.events.AnniversaryEvent;
	import com.skt.common_hr.main.events.NoticeEvent;
	import com.skt.common_hr.main.events.SearchEvent;
	import com.skt.common_hr.main.events.SelApprovalEvent;
	import com.skt.common_hr.main.model.AnniverProxy;
	import com.skt.common_hr.main.model.MyApprovalProxy;
	import com.skt.common_hr.main.model.MyInfoProxy;
	import com.skt.common_hr.main.model.NoticeProxy;
	import com.skt.common_hr.main.model.SiteLinkProxy;
	import com.skt.common_hr.main.model.vo.AuthorityVO;
	import com.skt.common_hr.main.model.vo.LoginVO;
	import com.skt.common_hr.main.model.vo.MainNoticeVO;
	import com.skt.common_hr.main.view.components.Home;
	import com.skt.common_hr.main.view.components.NoticeView;
	
	import flash.events.Event;
	import flash.external.ExternalInterface;
	
	import mx.collections.ArrayCollection;
	import mx.containers.VBox;
	import mx.managers.PopUpManager;
	import mx.resources.ResourceManager;
	
	import org.puremvc.as3.multicore.interfaces.INotification;
	
	public class HomeMediator extends CommonMediator
	{
		public static const NAME:String = "HomeMediator";

		private var server:String = "";
		/**
		* 생성자
		* 
		* @param
		* @return void
		*/
		public function HomeMediator(viewComponent:Object=null)
		{
            super( NAME, viewComponent );
		}
		
		/**
		* View를 초기화 한다.
		*	- Event Handler를 설정한다.
		* @param
		* @return void
		*/
  		override protected function initializeView():void
 		{
 			view.visible = false;
			checkServer();

			if(Variables.company == "NOS") {
				view.logo_image = "assets/images/main_logo_nos.png";
			}
			else if(Variables.company == "SAC") {
				view.logo_image = "assets/images/main_logo_sac.png";
			}
			else if(Variables.company == "STC") {
				view.logo_image = "assets/images/main_logo_stc.png";
			}
 			//공지사항
 			view.addEventListener(NoticeEvent.NOTICE_DETAIL_DATA, onClickNotice);

 			//공지사항
 			var noticeProxy:NoticeProxy = facade.retrieveProxy(NoticeProxy.NAME) as NoticeProxy;
 			noticeProxy.load("4");
 			
 			//기념일
 			var anniverProxy:AnniverProxy = facade.retrieveProxy(AnniverProxy.NAME) as AnniverProxy;
 			anniverProxy.load(Variables.myPernr);
			
			// 결재함
			var approvalProxy:MyApprovalProxy = facade.retrieveProxy(MyApprovalProxy.NAME) as MyApprovalProxy;
			approvalProxy.load(Variables.myPernr);
			setEventListener();
			
			// SiteLink
			var linkProxy:SiteLinkProxy = facade.retrieveProxy(SiteLinkProxy.NAME) as SiteLinkProxy
			linkProxy.load();
			
 		}
 		
		private function setEventListener():void
		{
 			view.addEventListener(Home.EVENT_LOGOUT, onLogout);
 			view.addEventListener(AppMenuEvent.SELECTED_MENU, onSelectedMenu);				// 메뉴 클릭
 			view.addEventListener(NoticeEvent.NOTICE_DETAIL_DATA, onClickNotice);			//공지사항
 			view.addEventListener(AnniversaryEvent.ANNIVER_DETAIL_DATA, onAnniverPopup);	//기념일
 			view.addEventListener(SelApprovalEvent.SELECTED_APPROVAL, onSelApproval);
 			view.addEventListener(SearchEvent.SEARCH_KEYWORD, onClickSearch);
		}

		private function checkServer():void
		{
			server = ExternalInterface.call("serverType");
		}


		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Process MVC Messages
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
		/**
		* 본 Class에서 처리해야할 Noti들을 등록한다.
		* 
		* @param
		* @return void
		*/
		override public function listNotificationInterests():Array 
		{
			return [
					Messages.ACTIVATE_MODULE,
					ApplicationFacade.LOAD_PROFILE_COMPLETE,
					ApplicationFacade.LOAD_ANNIVER_LIST_COMPLETE,
					ApplicationFacade.LOAD_ANNIVER_LIST_FAILED,
					ApplicationFacade.LOAD_VIEW_ANNIVER_LIST_COMPLETE,
					ApplicationFacade.LOAD_VIEW_ANNIVER_LIST_FAILED,
					ApplicationFacade.LOAD_NOTICE_MAINLIST_COMPLETE,
					ApplicationFacade.LOAD_NOTICE_MAINLIST_FAILED,
					MyApprovalProxy.LOAD_MYAPPROVAL_COMPLETE,
					MyApprovalProxy.LOAD_MYAPPROVAL_FAILED,
					SiteLinkProxy.LOAD_SITELINK_COMPLETE,
					SiteLinkProxy.LOAD_SITELINK_FAILED
					];
		}
		

		/**
		* Noti별로 처리한다.
		* 
		* @param
		* @return void
		*/
		override public function handleNotification(note:INotification):void
		{
			switch(note.getName()) 
			{
				case Messages.ACTIVATE_MODULE:
					view.bSelectedMenu = false;
		 			var noticeProxy:NoticeProxy = facade.retrieveProxy(NoticeProxy.NAME) as NoticeProxy;
		 			noticeProxy.load("4");
					// 결재함
					var approvalProxy:MyApprovalProxy = facade.retrieveProxy(MyApprovalProxy.NAME) as MyApprovalProxy;
					approvalProxy.load(Variables.myPernr);
					trace("activated home");
					break;
				case ApplicationFacade.LOAD_PROFILE_COMPLETE:
					setAuthority(note.getBody() as MyInfoProxy);
					view.welcome_message = buildWelcomeMessage((note.getBody() as MyInfoProxy).profile);
					view.visible = true;
					break;
				case ApplicationFacade.LOAD_VIEW_ANNIVER_LIST_COMPLETE:
					onAnniverViewLoad(note.getBody() as AnniverProxy);
					break;
				case ApplicationFacade.LOAD_VIEW_ANNIVER_LIST_FAILED:
					break;
				case ApplicationFacade.LOAD_ANNIVER_LIST_COMPLETE:
					view.anniverList = AnniverProxy(note.getBody()).annList;
					break;
				case ApplicationFacade.LOAD_ANNIVER_LIST_FAILED:
					break;
				case ApplicationFacade.LOAD_NOTICE_MAINLIST_COMPLETE:
					view.noticeList = NoticeProxy(note.getBody()).mainArr;
					if(view.noticeList.length==0) {
						var vo:MainNoticeVO = new MainNoticeVO();
						vo.CONTENT_IDX = "";
				 		vo.TITLE		= "공지사항이 없습니다.";
				 		view.noticeList.addItem(vo);
					}
					break;
				case ApplicationFacade.LOAD_NOTICE_MAINLIST_FAILED:
					break;
				case MyApprovalProxy.LOAD_MYAPPROVAL_COMPLETE:
					view.wNum = MyApprovalProxy(note.getBody()).WNUM;
					view.sNum = MyApprovalProxy(note.getBody()).SNUM;
					view.bNum = MyApprovalProxy(note.getBody()).BNUM;
					break;
				case MyApprovalProxy.LOAD_MYAPPROVAL_FAILED:
					view.wNum = 0;
					view.sNum = 0;
					break;
				case SiteLinkProxy.LOAD_SITELINK_COMPLETE:
				case SiteLinkProxy.LOAD_SITELINK_FAILED:
					view.siteLinkArr = SiteLinkProxy(note.getBody()).links;
					break;
				default:
					trace(NAME + " 처리 안된 Noti가 검출됨 : " + note.getName());
					break;
			}
		}

		private function buildWelcomeMessage(vo:LoginVO):String
		{
			var message:String = ResourceManager.getInstance().getString("HrMain", "WELCOME_MSG");
			if(message.search("%p")>= 0) {
				message = message.replace("%p", "<b>"+vo.ENAME+"</b>");
			} 
			if(server!=null && server!="PROD") {
				message += "("+server+")";
			}
			return message;
		}
		
		private function setAuthority(proxy:MyInfoProxy):void
		{
			for each(var menu:Object in AppModuleManager.modules)
			{
				if(menu[0] != AppModuleManager.MODULE_KEY_MAIN) {	// 메인 모듈은 제외
					menu.authority = findAuthority(proxy.authority, menu[0]);
					if(menu.authority == null) {
					//if(menu.authority == null && menu[0]!="REGUIDE") {
						removeMenuFromView(menu);
					} 
					else {
						view[menu[0]+"01"].visible = true;
						view[menu[0]+"01"].includeInLayout = true;
						view[menu[0]+"02"].visible = true;
						view[menu[0]+"02"].includeInLayout = true;						
					}
				}
			}
		}

		private function findAuthority(authArr:ArrayCollection, id:String):AuthorityVO
		{
			for each(var vo:AuthorityVO in authArr)
			{
				/* trace("vo.EMENU :" + vo.EMENU); */
				if(vo.EMENU==id) {
					return vo; //vo.EMERL;
				}
			}
			return null;
		}

		private function removeMenuFromView(menu:Object):void
		{
			if(view[menu[0]+"01"].parent == null) {
				return;
			}
//			var box1:VBox = view[menu[0]+"01"].parent;
//			var box2:VBox = view[menu[0]+"02"].parent;
			
			if(VBox(view[menu[0]+"01"].parent) != null) {
				VBox(view[menu[0]+"01"].parent).height = VBox(view[menu[0]+"01"].parent).height - 16;  
			}
			if(VBox(view[menu[0]+"01"].parent) != null) {
				VBox(view[menu[0]+"02"].parent).height = VBox(view[menu[0]+"02"].parent).height - 16;
			}
			
			view[menu[0]+"01"].parent.removeChild(view[menu[0]+"01"]);
			view[menu[0]+"02"].parent.removeChild(view[menu[0]+"02"]);
			//box1.height = box1.height - 20;
			//box2.height = box2.height - 20;
			/* 
			VBox(view["boxMenu1"]).validateSize(true);
			VBox(view["boxMenu2"]).validateSize(true);
			VBox(view["boxMenu3"]).validateSize(true);
			VBox(view["boxMenu4"]).validateSize(true);
			VBox(view["boxMenu1"]).validateNow();
			VBox(view["boxMenu2"]).validateNow();
			VBox(view["boxMenu3"]).validateNow();
			VBox(view["boxMenu4"]).validateNow();			
 */
			if(menu[0]==AppModuleManager.MODULE_KEY_SEARCH) {
				view.boxSearch.visible = false;
			}
		}




 		private function onSelectedMenu(event:AppMenuEvent):void
 		{
 			facade.sendNotification(Messages.EXECUTE_MODULE, event.menuId);
 		}
 		
 		private function onLogout(event:Event):void
 		{
 			facade.sendNotification(Messages.LOGOUT);
 		}
 		
		private function onClickNotice(event:NoticeEvent):void
		{
			if(event.vo == null) {		// more버튼이 눌렸을 때
				popUpNoticeView("");
			}
			else {
				if(event.vo.CONTENT_IDX == "") {		// 공지사항이 없는 경우임..
					return ;
				}
				popUpNoticeView(event.vo.CONTENT_IDX);
	 		}
		}

		//공지사항
		private var noticeView:NoticeView = null;
		private function popUpNoticeView(index:String):void
		{
			var noticeMediator:NoticeMediator;
			
			if(noticeView==null) {
	 			noticeView = PopUpManager.createPopUp(view.root, NoticeView, true) as NoticeView;
	 			PopUpManager.centerPopUp(noticeView);

	 			noticeMediator = new NoticeMediator(noticeView);
	 			facade.registerMediator(noticeMediator);
			}
			else {
				PopUpManager.addPopUp(noticeView, view.root, true);
				noticeMediator = facade.retrieveMediator(NoticeMediator.NAME) as NoticeMediator;
			}  			
			noticeView.setFocus();
 			noticeMediator.exec(index);
		}
 
 		//기념일
		private function onAnniverPopup(event:Event):void
		{
			var viewAnniverProxy:AnniverProxy = facade.retrieveProxy(AnniverProxy.NAME) as AnniverProxy;
 			viewAnniverProxy.viewload(Variables.myPernr);
		}
		
		private function onAnniverViewLoad(proxy:AnniverProxy):void
		{
 			view.anniverArr._dataProvider = proxy.viewAnnList;
 			PopUpManager.addPopUp(view.anniverArr, view, true);
 			PopUpManager.centerPopUp(view.anniverArr);
		}

		private function onSelApproval(event:SelApprovalEvent):void
		{
			Variables.moduleParams = new Object();
			Variables.moduleParams["SELECTED_APPROVAL_TYPE"] = event.selID;
			
			// 사전근무승인으로 98로 하드코딩
			if(event.selID==98) {
				facade.sendNotification(Messages.EXECUTE_MODULE, AppModuleManager.MODULE_KEY_HOLOTORDNOS);
			}else {
				facade.sendNotification(Messages.EXECUTE_MODULE, AppModuleManager.MODULE_KEY_APPROVAL);	
			}
			
		}
		
		private function onClickSearch(event:SearchEvent):void
		{
			Variables.moduleParams = new Object();
			Variables.moduleParams["KEYWORD"] = event.keyword;
			facade.sendNotification(Messages.EXECUTE_MODULE, AppModuleManager.MODULE_KEY_SEARCH);
		}


       private function get view():Home
        {
            return viewComponent as Home;
        }
	}
}